<?php
require_once dirname(__FILE__) . '/config.php';
require_once 'functions/sql.php';
$sql = new sql();
$sql->connect();
// Set up the IPP instance
$IPP = new QuickBooks_IPP($dsn);
// Get our OAuth credentials from the database
$creds = $IntuitAnywhere->load($the_username, $the_tenant);
// Tell the framework to load some data from the OAuth store
$IPP->authMode(
        QuickBooks_IPP::AUTHMODE_OAUTH, $the_username, $creds);

// This is our current realm
$realm = $creds['qb_realm'];
// Load the OAuth information from the database
if ($Context = $IPP->context()) {
    // Set the IPP version to v3 
    $IPP->version(QuickBooks_IPP_IDS::VERSION_3);
    $ItemService = new QuickBooks_IPP_Service_Item();
    $SalesReceiptService = new QuickBooks_IPP_Service_SalesReceipt();
    $SalesReceipt = new QuickBooks_IPP_Object_SalesReceipt();
    //$SalesReceipt->setDocNumber($lastpaymentid);
    $SalesReceipt->setTxnDate(date('Y-m-d h:i:s'));
    $SalesReceipt->setPaymentRefNum($transaction_id);
    if($payment_type == 'paypal'){
        $pay_Ref = '4';//10
    }else{
        $pay_Ref = '3';
    }
	//$pay_Ref = '3';
    $SalesReceipt->setPaymentMethodRef($pay_Ref);


    $Billemail = new QuickBooks_IPP_Object_BillEmail();
    $Billemail->setEmailStatus('NeedToSend');
    //$Billemail->setIsToBeEmailed(true);
    $Billemail->setAddress($user_email);



    $count = count($_SESSION['shoping_cart']);
    $i = 1;
    $total_Amount ='';
    $Discount_price = 0;
    $cat_match_count = 1;
    $cat_match_qty = 1;
    $coupon_applied = '';
    $coupon_product = '';
    $coupon_category = '';
    $Discount_code = '';
    
    
    if (isset($_SESSION['coupon_detail'])) {
        $Discount_price = "-".$_SESSION['coupon_detail']['coupon_price'];
        $Discount_code = $_SESSION['coupon_detail']['coupon_code'];
        if ($_SESSION['coupon_detail']['coupon_applied'] == 'per_item') {
            $cat_match_count = 0;
            $cat_match_qty = 0;
            $coupon_applied = 'per_item';
            $coupon_category = $_SESSION['coupon_detail']['coupon_category'];
            $coupon_product = $_SESSION['coupon_detail']['coupon_product'];
        }
    }
    foreach ($_SESSION['shoping_cart'] as $key => $value) {
        $total_Amount += $value['prd_price'] * $value['prd_qty'];
        if (($value['prd_cat_id'] == $coupon_category) && $coupon_applied == 'per_item' ) {
            $cat_match_count +=1;
            $cat_match_qty += $value['prd_qty'];
        }
        if (($value['prd_id'] == $coupon_product) && ($coupon_applied == 'per_item')) {
            $cat_match_count +=1;
            $cat_match_qty += $value['prd_qty'];
        }
        
        $Item = new QuickBooks_IPP_Object_Item();
        $product_name = substr($value['prd_name'],0,50) . "[" . $value['prd_code'] . "]";
        $Item->setName($product_name);
        $Item->setDescription($value['prd_name']);
      //  $Item->setIncomeAccountRef('49');
        $Item->setUnitPrice($value['prd_price']);
        $items = $ItemService->query($Context, $realm, "SELECT * FROM Item WHERE Name = '" . $product_name . "' ");
        //$Item = $items[0];
        // Update the name of the item
        //$Item->setName($Item->getName() . ' ' . mt_rand(0, 1000));
        $quick_book_id = '';
        if (count($items) > 0) {
            foreach ($items as $Item) {
                $quick_book_id = $Item->getId();
                $Item->setDescription($value['prd_name']);
                $Item->setUnitPrice($value['prd_price']);
                $updateresp = $ItemService->update($Context, $realm, $Item->getId(), $Item);
            }
        }

        //$Item->setType('Inventory');
        //$Item->setIncomeAccountRef('53');
        if ($quick_book_id != '') {
            $resp = $quick_book_id;
        } else {
            $resp = $ItemService->add($Context, $realm, $Item);
        }
        
        
		
        if ($resp) {
              
            $product_id = $resp;
            /*$updatedata = array(
                "quick_book_id" => $product_id,
            );
            $update = $sql->update('tbl_product', $updatedata, array("prd_id" => $value['prd_id']));
            */$Line = new QuickBooks_IPP_Object_Line();
            $Line->setDetailType('SalesItemLineDetail');
            $Line->setAmount($value['prd_price'] * $value['prd_qty']);
            $Line->setDescription($value['prd_name']);

            $SalesItemLineDetail = new QuickBooks_IPP_Object_SalesItemLineDetail();
            $SalesItemLineDetail->setItemRef($resp);
            //$SalesItemLineDetail->setEmailStatus('test@gmail.com');
            $SalesItemLineDetail->setUnitPrice($value['prd_price']);
            $SalesItemLineDetail->setQty($value['prd_qty']);
            
            //$servicedate = date('Y-m-d');
            //$jamesDate = date('22/09/2014');
            // $mtDate = date('Y-m-d');
            //$jamesDate = date($mtDate);
            //$SalesItemLineDetail->setServiceDate($servicedate);
            // $SalesItemLineDetail->setServiceDate(date('Y-m-d', strtotime("+1 day")));

            $Line->addSalesItemLineDetail($SalesItemLineDetail);
			//echo $last_quickbook_id;exit;
            $SalesReceipt->addLine($Line);
            $SalesReceipt->addBillEmail($Billemail);
            $SalesReceipt->setCustomerRef($last_quickbook_id);
			$SalesReceipt->setCustomerMemo('Total includes all applicable taxes.');
            
        } else {
            print($ItemService->lastError($Context));
        }
    
        $i++;
        }
    //Add Coupon in quickbook
        if (isset($_SESSION['coupon_detail'])) {
            $product_coupon_name = "Discount Code - ".$Discount_code;
            $product_coupon_price = $Discount_price;
            $Line = new QuickBooks_IPP_Object_Line();
            $Line->setDetailType('SalesItemLineDetail');
            $items = $ItemService->query($Context, $realm, "SELECT * FROM Item WHERE Name = '" . $product_coupon_name . "' ");
            $cpn_quick_book_id = '';
            if (count($items) > 0) {
                foreach ($items as $Item) {
                $cpn_quick_book_id = $Item->getId();
                }
            }
            $Line->setAmount($product_coupon_price * $cat_match_qty);
            $Line->setDescription($product_coupon_name);
            $SalesItemLineDetail = new QuickBooks_IPP_Object_SalesItemLineDetail();
            $SalesItemLineDetail->setItemRef($cpn_quick_book_id);
            $SalesItemLineDetail->setUnitPrice($product_coupon_price);
            $SalesItemLineDetail->setQty($cat_match_qty);
            $Line->addSalesItemLineDetail($SalesItemLineDetail);
            $SalesReceipt->addLine($Line);
            $SalesReceipt->addBillEmail($Billemail);
			$SalesReceipt->setCustomerRef($_SESSION['CHECKOUT_DATA']['qb_customer_id']);
            $SalesReceipt->setCustomerMemo('Total includes all applicable taxes.');

        }
        
    
        
        if ($resp = $SalesReceiptService->add($Context, $realm, $SalesReceipt)) {
       // print('Our new SalesReceiptService ID is: [' . $resp . ']');
         $saleId1 = str_replace("{-","",  $resp);
         $saleId = str_replace("}", "", $saleId1);

        $salesreceipts = $SalesReceiptService->query($Context, $realm, "SELECT Id,DocNumber FROM SalesReceipt where Id = '" . $saleId . "'");
        
        
        foreach ($salesreceipts as $SalesReceipt) {
           $DocNumber = $SalesReceipt->getDocNumber();
        }
        $_SESSION['CHECKOUT_DATA']['qb_salerecepit_id'] = $resp;
        $_SESSION['CHECKOUT_DATA']['qb_sale_docnumber'] = $DocNumber;
        /*$updatesalesdata = array(
            "salesreceiptid" => $resp,
            "DocNumber" => $DocNumber,
        );
        $updatepaymentorder = $sql->update('payment_order', $updatesalesdata, array("pt_id" => $lastpaymentid));
        */


        unset($_SESSION['shoping_cart']);
        unset($_SESSION['coupon_detail']);
        header("Location: " . URL . "thankyou/" . $lastpaymentid);
    } else {
        die($SalesReceiptService->lastError());
    }
} else {
    die('Unable to load a context...?');
}
?>